<template>
  <div class="avue-ueditor" >
    <div :id="id" style="background-color: #00a680"/>
    <div v-if="show"
         class="wangEditor_html-content">
      <div class="wangEditor_html-header">
        <span class="wangEditor_html-close"
              @click="show=false">x</span>
      </div>
      <textarea v-model="text"/>
    </div>
    <!-- 添加加载动画 -->
    <div v-if="loading" class="shadow"></div>
    <div v-if="loading" class="loading">
      <span>上传中...</span>
    </div>
  </div>
</template>
<script>
import {getClient} from './upload/ali'
import {getToken} from './upload/qiniu'
import {getAsVal, HTMLFormat, validatenull, uuid} from './upload/util'
import Plugin from './plugin.js'
import E from 'wangeditor'

export default {
  name: 'AvueUeditor',
  props: {
    data: {
      type: Object,
      default: () => {
        return {}
      },
    },
    headers: {
      type: Object,
      default: () => {
        return {}
      },
    },
    customConfig: {
      type: Object,
      default: () => {
        return {}
      },
    },
    propsHttp: {
      type: Object,
      default: () => {
        return {}
      },
    },
    options: {
      type: Object,
      default: () => {
        return {}
      },
    },
    ali: {
      type: Object,
      default: () => {
        return {}
      },
    },
    qiniu: {
      type: Object,
      default: () => {
        return {}
      },
    },
    oss: String,
    action: String,
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: ''
    },
    isVmodel: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      id: 'avue-ueditor-' + uuid(),
      text: '',
      html: '',
      show: false,
      editor: '',
      loading: false, // 添加 loading 属性
      isChange: false,
      count: 0 // 用来保证首次加载拿到value
    }
  },
  computed: {
    fileName() {
      return this.propsHttp.fileName || 'file'
    },
    homeUrl() {
      return this.propsHttp.home || ''
    },
    resKey() {
      return this.propsHttp.res
    },
    domId() {
      return '#' + this.id
    },
    imgFlag() {
      return this.img.url == ''
    },
    isImg() {
      return this.img.obj.src
    },
    urlKey() {
      return this.propsHttp.url || 'url'
    },
    isHtml() {
      return validatenull(this.customConfig.showHtml) ? true : this.customConfig.showHtml
    },
    isQiniuOSS() {
      return this.oss === 'qiniu'
    },
    isAliOSS() {
      return this.oss === 'ali'
    }
  },
  watch: {
    disabled(val) {
      if (val) {
        this.editor.disable()
      } else {
        this.editor.enable()
      }
    },
    text(val) {
      this.text = HTMLFormat(val)
      if (this.count == 0 && this.isVmodel) {
        // 通过count和isVmodle共同限制首次加载，isVmodel是当作组件使用时用到vmodel必传,<AvueUeditor :disabled="isView" v-model="editForm.instruction" :isVmodel="true"/>
        this.editor.txt.html(this.text)
        this.count++
      }
      if (!this.isChange) {
        this.editor.txt.html(this.text)
      }
      this.$emit('input', this.text)
      this.$emit('change', this.text)
    },
    value(newVal) {
      this.text = newVal
    },
  },
  mounted() {
    this.initEdit()
  },
  methods: {
    initEdit() {
      this.editor = new E(this.domId)
      if (this.isHtml) {
        E.registerMenu('Plugin', Plugin(this))
      }
      this.editor.config.zIndex = 100
      this.editor.config.menuTooltipPosition = 'down'
      this.editor.config.placeholder = this.placeholder
      this.editor.config.showFullScreen = true
      this.editor.config.onfocus = () => {
        this.$emit('focus', this.text)
      }
      this.editor.config.onblur = (html) => {
        this.isChange = false
        this.$emit('blur', html)
      }
      this.editor.config.onchange = (html) => {
        this.isChange = true
        this.text = HTMLFormat(html)
        this.$emit('input', this.text)
        this.$emit('change', this.text)
      }
      this.editor.config.emotions = [
        {
          title: 'emoji',  // tab 的标题
          type: 'emoji', // 'emoji' / 'image'
          // emoji 表情，content 是一个数组即可
          content: '😀 😃 😄 😁 😆 😅 😂 😊 😇 🙂 🙃 😉 😓 😪 😴 🙄 🤔 😬 🤐'.split(/\s/),
        }
      ]
      this.initUploadImg()
      this.editor.config = Object.assign(
        this.editor.config,
        this.customConfig
      )
      this.editor.create()
      if (this.disabled === true) this.editor.disable()
      this.editor.txt.html(this.value)
    },
    initUploadImg() {
      const callback = (file, insert) => {
        this.uploadFile(file[0]).then((res) => {
          insert(res)
        })
      }
      this.editor.config.customUploadVideo = callback
      this.editor.config.customUploadImg = callback
    },
    uploadFile(file) {
      console.log('编辑富文本')
      this.loading = true; // 显示加载状态
      return new Promise((resolve, reject) => {
        const headers = Object.assign(this.headers, {
          'Content-Type': 'multipart/form-data',
        })
        let oss_config = {}
        let client
        let param = new FormData()
        let url = this.action
        param.append(this.fileName, file)
        Object.keys(this.data).forEach(ele => {
          param.append(ele, this.data[ele])
        })
        if (this.isQiniuOSS) {
          console.log('1')
          oss_config = this.qiniu
          const token = getToken(oss_config.AK, oss_config.SK, {
            scope: oss_config.scope,
            deadline:
              new Date().getTime() + oss_config.deadline * 3600,
          })
          param.append('token', token)
          url = 'http://up.qiniu.com/'
        } else if (this.isAliOSS) {
          console.log('2')
          oss_config = this.ali
          client = getClient({
            region: oss_config.region,
            endpoint: oss_config.endpoint,
            accessKeyId: oss_config.accessKeyId,
            accessKeySecret: oss_config.accessKeySecret,
            bucket: oss_config.bucket,
          })
        }
        (() => {
          if (this.isAliOSS) {
            console.log('3')
            return client.put(file.name, file)
          } else {
            console.log('5')
            return this.$axios.post(url, param, {headers})
          }
        })()
          .then((res) => {
            console.log('8')
            let list = {}
            var result = ''
            if (this.isAliOSS) {
              list = res
              result = list.url
            } else if (this.isQiniuOSS) {
              list = res.data
              list.key = oss_config.url + list.key
              result = list.key
            } else {
              if (typeof (this.resKey) === 'function') {
                list = this.resKey(res.data);
              } else {
                list = getAsVal(res.data, this.resKey);
                list = list[this.urlKey]
              }
            }
            var html = this.homeUrl + list
            resolve(html)
          })
          .catch((err) => {
            reject(err)
          }).finally(() => {
          this.loading = false; // 隐藏加载状态
        });
      })
    },
    getUEContent() {
      return this.editor.txt.html()
    }
  }
}
</script>
<style>
.wangEditor_html {
  color: #999;
  font-size: 14px;
  font-weight: bold;
}

.wangEditor_html-content {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 2048;
  padding: 0 20px 20px 20px;
  background-color: #fff;
  box-sizing: border-box;
}

.wangEditor_html-content textarea {
  width: 100%;
  height: 100%;
  border-color: #ccc;
  border-radius: 5px;
  padding: 5px;
}

.wangEditor_html-header {
  padding: 5px 0;
  text-align: right;
}

.wangEditor_html-close {
  color: #333;
  font-weight: bold;
  font-size: 22px;
}

.shadow{
  position: fixed;
  z-index: 2049;
  top: 0;
  bottom:0;
  right: 0;
  left: 0;
  background-color: rgba(5, 1, 1, 0.5);
  /*transform: translate(-50%, -50%);*/
}

.loading {
  position: fixed;
  z-index: 2051;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 10px;
  border-radius: 4px;
}
</style>
